local M = {}

M.dependencies = {
    "https://github.com/neovim/nvim-lspconfig",
    "https://github.com/hrsh7th/cmp-nvim-lsp",
    "https://github.com/hrsh7th/cmp-buffer",
    "https://github.com/hrsh7th/cmp-path",
    "https://github.com/hrsh7th/cmp-cmdline",
    "https://github.com/L3MON4D3/LuaSnip",
    "https://github.com/saadparwaiz1/cmp_luasnip"
}

function M:setup_cmp()
    self.cmp = require('cmp')
    local cmp = self.cmp

    cmp.setup({
        snippet = {
            expand = function(args)
                require('luasnip').lsp_expand(args.body)
            end,
        },
        window = {
            completion = {
                winhighlight = "Normal:Pmenu,FloatBorder:Pmenu,Search:None",
            }
        },
        mapping = cmp.mapping.preset.insert({
            ['<C-b>'] = cmp.mapping.scroll_docs(-4),
            ['<C-f>'] = cmp.mapping.scroll_docs(4),
            ['<C-Space>'] = cmp.mapping.complete(),
            ['<C-e>'] = cmp.mapping.abort(),
            ["<CR>"] = cmp.mapping.confirm({ select = true }),
        }),
        sources = cmp.config.sources({
            { name = 'nvim_lsp' },
            { name = 'luasnip' },
        }, {
            { name = 'buffer' },
        }),
    })
end

function M:setup_cmdlines()
    local cmp = self.cmp

    cmp.setup.cmdline({ '/', '?' }, {
        mapping = cmp.mapping.preset.cmdline(),
        sources = {
            { name = 'buffer' }
        }
    })

    cmp.setup.cmdline(':', {
        mapping = cmp.mapping.preset.cmdline(),
        sources = cmp.config.sources({
            { name = 'path' }
        }, {
            { name = 'cmdline' }
        })
    })
end

function M:setup_lspconfig()
    local capabilities = require('cmp_nvim_lsp').default_capabilities()
    local function setup_lang_server(name)
        require('lspconfig')[name].setup { capabilities = capabilities }
    end

    setup_lang_server('clangd')
    setup_lang_server('lua_ls')
    setup_lang_server('jedi_language_server')
    setup_lang_server('html')
    setup_lang_server('cssls')
    setup_lang_server('bashls')
    setup_lang_server('zls')
    setup_lang_server('texlab')
    setup_lang_server('ltex')
end

M.lazy_def = {
    "https://github.com/hrsh7th/nvim-cmp",
    dependencies = M.dependencies,
    config = function()
        M:setup_cmp()
        M:setup_cmdlines()
        M:setup_lspconfig()
    end,
}

return M
